package org.example.route.task;

import lombok.extern.slf4j.Slf4j;
import org.example.route.constant.OrderConstant;
import org.example.route.mapper.OrderMapper;
import org.example.route.model.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 *
 * 用于处理定时任务
 *
 * **/
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;


    //处理超时订单的方法
    //每天
    @Scheduled(cron = "0 0 0/12 * * ?")
    @Transactional
    public void processTimeOutOrder() {
        log.info("定时处理超时订单，{}", LocalDateTime.now());

        //获得状态和时间
        List<Order> ordersList = orderMapper.getByStatusAndOrderTimeLT(OrderConstant.WAIT_PAY, LocalDateTime.now().minusDays(1));
       // List<Order> orders = orderMapper.getByStatus(OrderConstant.CANCEL);
        //ordersList.addAll(orders);

        if (!Objects.isNull(ordersList) && !ordersList.isEmpty()) {
            ordersList.stream().forEach(order ->
                    {
                       order.setStatus(OrderConstant.CANCEL);
                       orderMapper.update(order);
                    }
            );
        }
    }


    //处理已经坐过站的订单
    //每天的午夜执行
    @Scheduled(cron = "0 0 0 * * ?")
    @Transactional
    public void processEndOrder()
    {
        log.info("处理购买过但是已经坐过站的订单,{}",LocalDateTime.now());
        List<Order> orders = orderMapper.getByStatusAndEndTimeLT(OrderConstant.PAYED, LocalDateTime.now());

        orders.forEach(order -> {
            order.setStatus(OrderConstant.CANCEL);
        });

        //保存信息
        orders.stream().forEach(
                order -> {
                    orderMapper.update(order);
                }
        );
    }


    //TODO 发车前三小时提醒用户

}
